package database

import (
	"apedge/dao"
	"apedge/pkg/configs"
	"apedge/pkg/loggers"
	"database/sql"
	"fmt"

	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/postgres"
)

var Db *gorm.DB
var logger = loggers.LogInstance()

func InitDatabase(config configs.AppConfig) {

	dbConf := config.Db

	sslmode := "require"
	if len(dbConf.Sslmode) > 0 {
		sslmode = dbConf.Sslmode
	}
	db, err := sql.Open("postgres", fmt.Sprintf("host=%s port=%d user=%s password=%s sslmode=%s", dbConf.Host, dbConf.Port, dbConf.Username, dbConf.Password, sslmode))
	if err != nil {
		panic(err)
	}
	defer db.Close()
	exist := 0
	query := "SELECT count(1) FROM pg_database WHERE datname = $1"

	if err = db.QueryRow(query, dbConf.Database).Scan(
		&exist,
	); err != nil {
		logger.Info(err.Error())
		panic(err)
	}
	logger.Info(exist)

	if exist == 0 {
		logger.Info(dbConf.Database)
		_, err = db.Exec("CREATE DATABASE " + dbConf.Database)
		if err != nil {
			logger.Info(err.Error())
			panic(err)
		}
	}

	Db, err = gorm.Open("postgres", fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s", dbConf.Host, dbConf.Port, dbConf.Username, dbConf.Password, dbConf.Database, sslmode))
	if err != nil {
		logger.Info(err.Error())
		panic(err)
	}

	logger.Info("PostgreSQL connected success")
	Db.DB().SetMaxOpenConns(dbConf.MaxOpenConns)
	Db.DB().SetMaxIdleConns(dbConf.MaxIdleConns)
}

func CreateTableIfNotExists(modelType interface{}) error {
	if !Db.HasTable(modelType) {
		return Db.CreateTable(modelType).Error
	}
	return nil
}

func InitTables() {
	CreateTableIfNotExists(dao.ApedgeNode{})
	CreateTableIfNotExists(dao.ApedgeNodeGroup{})
	CreateTableIfNotExists(dao.ApedgeInference{})
	CreateTableIfNotExists(dao.ApedgeServiceNode{})
}
